package stewardapplet

import (
	"github.com/gin-gonic/gin"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/ticket"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wxpay"
)

func HandleTicketCreateOrders(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.CreateStewardOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ClientIp = ctx.ClientIP()
	param.UserId = userId

	if param.Openid == "" || param.DeviceSn == "" {
		Response(ctx)("参数错误,请重新扫码", CodeError, nil)(OK)
		return
	}

	param.Key = "/ticket"
	respData := &wxpay.PayData{}
	resultData := &wxpay.PayData{}
	orderLogic := logic.NewOrderLogic()

	param.Amount = utils.IfTrueInt(param.Amount > 0, param.Amount, 1)
	if respData, err = orderLogic.HandleWxStewardUnifiedOrder(param); err != nil {
		Response(ctx)(err.Error(), CodeError, respData)(OK)
		return
	}
	resultData = orderLogic.HandleMakeSign(respData)
	_ = orderLogic.HandleWxStewardSetAgainOrder(orderLogic.TradeNo, resultData.ToJson())

	mInfo := memberdao.NewMemberDao().GetMemberInfoById(param.UserId).Unwrap().(*membermodel.MembersModel)
	insertInfo := &ticket.OrderDb{
		Appid:       mInfo.AppId,
		Openid:      mInfo.XcxOpenid,
		MemberId:    userId,
		TicketId:    param.TicketId,
		Price:       param.Amount,
		PayAmount:   param.Amount,
		TotalAmount: param.Amount,
		DayLen:      1,
		TicketNum:   1,
		IsDelete:    helper.TypeNumCommonStatusFalse,
		Status:      1,
		PayType:     2,
		TradeNo:     orderLogic.TradeNo,
		DeviceSn:    param.DeviceSn,
	}
	if data := dao.NewTicketDaoDao().CreateTicketOrders(insertInfo); data.Err != nil {
		Response(ctx)(data.Err.Error(), CodeInternalServerError, respData)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"pay":     resultData.ToJson(),
		"tradeNo": orderLogic.TradeNo,
		"donePay": param.Amount <= 0,
	})(OK)
}
